package com.googlecode.publicholiday.repository.file;

import com.googlecode.publicholiday.FileParser;
import com.googlecode.publicholiday.SimpleFileParser;
import com.googlecode.publicholiday.repository.ImmutablePublicHolidayRepository;
import org.joda.time.LocalDate;

import java.io.File;
import java.util.Collection;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class StaticFilePublicHolidayRepository implements ImmutablePublicHolidayRepository {

    private final Map<String, SortedSet<LocalDate>> dataStore;

    public StaticFilePublicHolidayRepository(File repository) throws Exception {
        this(repository, new SimpleFileParser());
    }

    public StaticFilePublicHolidayRepository(File repository, FileParser fileParser) throws Exception {
        dataStore = fileParser.parse(repository);
    }

    @Override
    public LocalDate find(String countryCode, LocalDate publicHoliday) {
        SortedSet<LocalDate> publicHolidays = dataStore.get(countryCode);
        if (publicHolidays != null && publicHolidays.contains(publicHoliday)) {
            return new LocalDate(publicHoliday);
        } else {
            return null;
        }
    }

    @Override
    public Collection<LocalDate> find(String countryCode, LocalDate startDate, LocalDate endDate) {
        SortedSet<LocalDate> publicHolidays = dataStore.get(countryCode);
        if (publicHolidays != null) {
            return publicHolidays.subSet(startDate, endDate);
        } else {
            return new TreeSet<LocalDate>();
        }
    }
}
